package com.ljt.yupictureddd.shared.manager.sharding;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;
import java.util.List;
import java.util.Properties;

public class PictureShardingAlgorithm implements StandardShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        // availableTargetNames是yaml里面写的actual-nodes有关，我yaml写的是picture，不是picture${0-999999999999}
        // picture是个固定的.

        // yaml里面写的column是spaceId，所以取出来的也是spaceId
        Long spaceId = preciseShardingValue.getValue();
        // 取出表名
        String logicTableName = preciseShardingValue.getLogicTableName();
        // 如果没有空间id，找不到对应的，为了不要复杂就直接返回逻辑表名就好了。
        if (spaceId == null){
            return logicTableName;
        }
        // 如果有空间id，就动态生成分表名
        String realTableName = "picture_" + spaceId;
        // 如果数据库中有就直接返回
        if (availableTargetNames.contains(realTableName)){
            return realTableName;
        }
        // 如果没有就直接返回逻辑表名
        return logicTableName;
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return List.of();
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }


}
